
package com.platform.modules.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.utils.Constant;
import com.platform.common.utils.Query;
import com.platform.common.utils.StringUtils;
import com.platform.modules.bk.entity.BkCustomerEntity;
import com.platform.modules.bk.service.BkCustomerService;
import com.platform.modules.mall.dao.MallUserSignRecordDao;
import com.platform.modules.mall.entity.MallUserEntity;
import com.platform.modules.mall.entity.MallUserSignRecordEntity;
import com.platform.modules.mall.entity.SignConfig;
import com.platform.modules.mall.service.MallUserIntegralLogService;
import com.platform.modules.mall.service.MallUserService;
import com.platform.modules.mall.service.MallUserSignRecordService;
import com.platform.modules.sys.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 用户签到记录Service实现类
 *
 * @author
 * @date 2019-07-02 18:15:12
 */
@Service("mallUserSignRecordService")
public class MallUserSignRecordServiceImpl extends ServiceImpl<MallUserSignRecordDao, MallUserSignRecordEntity> implements MallUserSignRecordService {
    @Autowired
    private MallUserService userService;
    @Autowired
    private MallUserIntegralLogService mallUserIntegralLogService;
    @Autowired
    private SysConfigService configService;
    @Autowired
    private BkCustomerService bkCustomerService;

    @Override
    public List<MallUserSignRecordEntity> queryAll(Map<String, Object> params) {
        return baseMapper.queryAll(params);
    }

    @Override
    public Page queryPage(Map<String, Object> params) {
        //排序
        params.put("sidx", "T.ID");
        params.put("asc", false);
        Page<MallUserSignRecordEntity> page = new Query<MallUserSignRecordEntity>(params).getPage();
        return page.setRecords(baseMapper.selectMallUserSignRecordPage(page, params));
    }

    @Override
    public boolean add(MallUserSignRecordEntity mallUserSignRecord) {
        return this.save(mallUserSignRecord);
    }

    @Override
    public boolean update(MallUserSignRecordEntity mallUserSignRecord) {
        return this.updateById(mallUserSignRecord);
    }

    @Override
    public boolean delete(String id) {
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(String[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public Map<String, Object> getSignByParams(String userId) {
        Map<String, Object> result = new HashMap<>();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int length = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        Integer[] list = getDefaultList(length + 1);

        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("type", "nowMonth");
        List<MallUserSignRecordEntity> userSignRecordVos = queryAll(map);
        if (userSignRecordVos != null && userSignRecordVos.size() > 0) {
            for (MallUserSignRecordEntity vo : userSignRecordVos) {
                calendar.setTime(vo.getSignTime());
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                list[day] = day;
            }
        }
        result.put("monthDaySize", length);
        result.put("calendarSignData", list);
        result.put("calendarSignDay", userSignRecordVos.size());
        return result;
    }

    @Override
    public boolean nowDaySigned(String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", id);
        //查询当天
        map.put("type", "nowDay");
        List<MallUserSignRecordEntity> userSignRecordVos = queryAll(map);
        if (null == userSignRecordVos || userSignRecordVos.size() == 0) {
            return false;
        }
        return true;
    }

    /**
     * 签到
     *
     * @param userEntity
     * @return
     */
    @Override
    @Transactional
    public BigDecimal userSign(MallUserEntity userEntity) {
        String id = userEntity.getId();
        //当天未签到
        if (!nowDaySigned(id)) {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", id);
            map.put("type", "nowWeek");
            List<MallUserSignRecordEntity> userSignRecordVos = queryAll(map);

            SignConfig config = configService.getConfigObject(Constant.SIGN_CONFIG_KEY, SignConfig.class);
            if ("0".equals(config.getStatus())) {
                return BigDecimal.valueOf(0);
            }
            // 签到积分，后台配置的
            BigDecimal integral = new BigDecimal(config.getPoints()[userSignRecordVos.size()]);

            MallUserSignRecordEntity vo = new MallUserSignRecordEntity();
            vo.setUserId(id);
            vo.setSignTime(new Date());
            vo.setSignIntegral(integral);
            save(vo);
            BigDecimal oldIntegral = userEntity.getSignAllIntegral();
            if (StringUtils.isNotBlank(userEntity.getCustomerNo())) {
                BkCustomerEntity customerEntity = bkCustomerService.getById(userEntity.getCustomerNo());
                if (customerEntity != null) {
                    oldIntegral = customerEntity.getAvailablePoints().add(userEntity.getSignAllIntegral());
                }
            }

            mallUserIntegralLogService.add(userEntity.getId(), integral, oldIntegral, Constant.IntegralType.INCOME, "签到");

            userService.update(new LambdaUpdateWrapper<MallUserEntity>()
                    .set(MallUserEntity::getSignAllIntegral, userEntity.getSignAllIntegral().add(integral))
                    .eq(MallUserEntity::getId, id));

            return integral;
        }
        return BigDecimal.valueOf(0);
    }

    private Integer[] getDefaultList(int length) {
        Integer[] result = new Integer[length];
        for (int i = 0; i < length; i++) {
            result[i] = null;
        }
        return result;
    }
}
